var timer, uploadSrc, controller, filter, order, search, items, currentInput, calendar, today, maintenancesCombo;
var pageToken = '';
var defaultPage = "#lines";
var maintenancesTextBoxes = ['description', 'duration'];
var equipmentsTextBoxes = ['tail-number', 'drop-date', 'available-date'];
var logTextBoxes = ['limit-date'];
var linesTextBoxes = ['description', 'drop-date', 'available-date'];
var debug = 0;

function loaded() {
    checkPageThread();
}

function checkPageThread() {
    var page;
    
    page = location.hash;
    if (page.length > 0) {
        page = page.substring(1);
    } else {
        document.location.replace(defaultPage);
    }
    if (pageToken != page) {
        var pageName = page.substr(0,1).toUpperCase() + page.substr(1)
        document.title = 'ADSI - ' + pageName;
        changePage(page);
        uploadSrc = 'upload' + pageName + '.jsp';
        pageToken = page;
    }
    timer = setTimeout('checkPageThread()', 250);
}

function loadAutocompleter () {
    var data = '{"controller" : "' + controller + '", "command" : "getFormattedSuggestions"}';
    new Ajax.Autocompleter("autocomplete", "autocomplete_choices", "logic?data=" + data);
}

function changePage(page) {
    $('container').innerHTML = '<span>Cargando...</span>';
    new Ajax.Updater('container', page + '.jsp', { method: 'get', evalScripts: true })
}

function back() {
    window.history.back();
}
function forward() {
    window.history.forward();
}

function showElement(elementName) {
    if (elementName == 'create' || elementName == 'advanced') {
        cancelElement('upload');
    } else if (elementName == 'upload') {
        $('upload').contentDocument.location.replace(uploadSrc);
        cancelElement('create');
        cancelElement('advanced');
        document.title = 'ADSI - ' + pageToken + ' - upload';
    }
    Effect.BlindDown(elementName); //Element.show(elementName);
}

function cancelElement(elementName) {
    var element = $(elementName);
    
    if (element) {
        var forms = element.select('form');
        for (i = 0; i < forms.length; i++) {
            forms[i].reset();
        }
    }
    if (elementName.match('parent.')) {
        var name = elementName.replace('parent.', '');
        element = parent.document.getElementById(name);
        new Effect.DropOut(element); //element.hide();
        parent.document.title = 'ADSI';
    }
    Effect.BlindUp(element); //Element.hide(elementName);
}

function serializeForm(form) {
    var data = form.serialize(true);
    
    doAjax(data);

    return false;
}

function doAjax(data) {
    data.controller = controller;
    data.order = order;
    data.filter = filter;
    
    if (data.command.match(/search/i)) {
        search = data;
        $('filter').selectedIndex = 1;
    }
    if (debug) alert(Object.toJSON(data));
    new Ajax.Request('logic',
    {
        method:'get',
        parameters: {'data' : Object.toJSON(data)},
        onSuccess: function(transport) {
            var response = transport.responseText || '{"ERROR" : "No response text"}';
            var data = response.evalJSON();
            if (debug) alert(response);
            if (data.render) {
                items = data.items;
                renderItems();
            } else if (!data.ERROR) {
                data.id = (data.subcontroller == "log" ? "i" :  "") + data.id;
                if (data.command == 'remove') {
                    $(data.id).remove();
                    return;
                } else if (data.command == 'edit') {
                    cancelEdit(data.id, data.list, data.subcontroller);
                    return;
                } else if (data.command == 'create') {
                    cancelElement('create');
                } else if (data.command == 'assign') {
                    //cancelElement('assign');
                }
                if (data.command == 'getMaintenances') {
                    buildMaintenancesCombo(data.maintenances);
                }  else if (data.command == 'getEquipmentMaintenances') {
                    buildEquipmentMaintenances(data.equipmentId, data.em);
                } else {
                    loadItems();
                }
            } else {
                alert(data.ERROR);
            }
        },
        onFailure: function(){alert('Communication problems.')}
    });
}

function createFromFile(filename, subcontroller) {
    new Ajax.Request('upload',
    {
        method:'get',
        parameters: {'filename' : filename, 'controller' : subcontroller},
        onSuccess: function(transport){
            var response = transport.responseText || 'false';
            if (eval(response)) {
                cancelElement('parent.upload');
                parent.document.location.reload();
            } else {
                $('container').innerHTML = "ERROR: Archivo corrupto";
            }
        }
    });
}

function changeFilter(selection) {
    filter = selection.options[selection.selectedIndex].value;
    
    if (filter == 'search' && !search) {
        filter = 'all';
        selection.selectedIndex = 0;
    } else if (filter == 'search') {
        doAjax(search);
    } else {
        loadItems();
    }
}

function changeOrder(selection) {
    order = selection.options[selection.selectedIndex].value;
    
    loadItems();
}

function loadItems() {
    var data = {command : "read"}
    doAjax(data);
}

function loadMaintenances() {
    var data = {command : "getMaintenances"}
    doAjax(data);
}

function buildMaintenancesCombo(maintenances) {
    maintenancesCombo = '<select name="maintenanceId">';
    for (i = 0; i < maintenances.length; i++) {
        maintenancesCombo += '<option value="' + maintenances[i].id + '">' + maintenances[i].description + '</option>';
    }
    maintenancesCombo += '</select>';
}

function loadEquipmentMaintenances(equipmentId) {
    var data = {command : "getEquipmentMaintenances", 'equipmentId' : equipmentId}
    doAjax(data);
}

function buildEquipmentMaintenances(equipmentId, em) {
    s = '' +
        '    <div class="border-top">' + 
        '        <table id="manager" border="1">' + 
        '            <tr>' + 
        '                <th>Descripción</th>' + 
        '                <th>Duración</th>' + 
        '                <th>Fecha límite</th>' + 
        '                <th><em>Acciones</em></th>' + 
        '            </tr>';
        
    for (i = 0; i < em.length; i++) {
        s += '' +
            '            <tr id="i' + em[i].id + '" ' + ((i % 2 == 0) ? 'class="gray"' : '' ) + '>'+ 
            '                <td>' + em[i].description + '</td>' + 
            '                <td>' + em[i].duration + '</td>' + 
            '                <td id="limit-datei' + em[i].id + '">' + em[i]['limit-date'] + '</td>' + 
            '                <td id="actionsi' + em[i].id + '">' + 
            '                    <button onclick="edit(\'i' + em[i].id + '\', \'log\')">Editar</button>' + 
            '                    <button onclick="del(\'i' + em[i].id + '\', \'log\')">Borrar</button>' + 
            '                </td>' + 
            '            </tr>';
    }
        
    s += '' +
        '        </table>' + 
        '    </div>' +    
        '</div><!--/item-->';
    
    $('em' + equipmentId).innerHTML = s;
}

function renderItems() {
    var html = '';
    
    if (controller == "Maintenances") {
        html += '<tr><th>Descripción</th><th>Duración</th><th><em>Acciones</em></th></tr>';
        for (i = 0; i < items.length; i++) {
            id = items[i].id;
            
            html += '<tr id ="' + id + '" ' + ((i % 2 == 0) ? 'class="gray"' : '' ) + '>';
            html += '<td id="description' + id + '">' + items[i].description + '</td>';
            html += '<td id="duration' + id + '">' + items[i].duration + '</td>';
            html += '<td id="actions' + id + '"><button onclick="edit(\'' + id + '\')">Editar</button> <button onclick="del(\'' + id + '\')">Borrar</button></td>';
            html += '</tr>'
        }
        $('manager').innerHTML = html;
    } else if (controller == "Equipments") {
        $('list').innerHTML = '';
        for (i = 0; i < items.length; i++) {
            $('list').innerHTML += renderEquipment(items[i]);
        }
        observeCalInputs();
    }  else if (controller == "Lines") {
        
    }
}

function getChecked(b) {
    //return (b == 'true') ? 'checked="checked"' : '';
}

function renderEquipment(e) {
    s = '' +
        '<div id="' + e.id + '" class="item">' +
        '<table class="wide clean-table">' +
        '        <tr>' +
        '            <td><h3 id="tail-number' + e.id + '">' + e['tail-number'] + '</h3></td>' +
        '            <td><input id="delivered' + e.id + '" type="checkbox" disabled="disabled" ' + /*getChecked(e.delivered)*/ + '/><label for="delivered' + e.id + '">Entregado</label></td>' + 
        '            <th id="actions' + e.id + '"><button onclick="edit(\'' + e.id + '\', \'equipment\')">Editar</button> <button onclick="del(\'' + e.id + '\', \'equipment\')">Borrar</button></th>' + 
        '        </tr>' + 
        '        <tr>' + 
        '            <td><strong>Fecha de alta: </strong><span>' + e['created-date'] + '</span></td>' + 
        '            <td><strong>Fecha de baja: </strong><span id="drop-date' + e.id + '">' + e['drop-date'] + '</span></td>' + 
        '            <td><strong>Disponibilidad: </strong><span id="available-date' + e.id + '">' + e['available-date'] + '</span></td>' + 
        '        </tr>' + 
        '        <tr>' + 
        '            <!--td colspan="3"><strong>STATUS:</strong> En mantenimiento</td-->' + 
        '        </tr>' + 
        '    </table>' +
        
        '    <div>' + 
        '        <span class="link big" onclick="showElement(\'assign' + e.id + '\')">Asignar mantenimiento</span>' + 
        '    </div>' + 
        '    <div id="assign' + e.id + '" style="display:none">' + 
        '        <form onsubmit="return serializeForm(this)">' + 
        '            <input type="hidden" name="command" value="assign"/>' + 
        '            <input type="hidden" name="equipmentId" value="' + e.id + '"/>' + 
        '            <table class="clean-table">' + 
        '                <tr>' + 
        '                    <th>Mantenimiento</th>' + 
        '                    <td>' + maintenancesCombo + '</td>' + 
        '                </tr>' + 
        '                <tr><th>Fecha límite</th><td class="cal"><input name="limit-date" type="textbox"/></td></tr>' + 
        '                <tr>' + 
        '                    <th></th>' + 
        '                    <td>' + 
        '                        <input type="submit" value="Agregar"/>' + 
        '                       <span class="link red" onclick="cancelElement(\'assign' + e.id + '\')">Cancelar</span>' + 
        '                    </td>' + 
        '                </tr>' + 
        '            </table>' + 
        '        </form>' + 
        '    </div>' +
        '<div id="em' + e.id + '">Cargando...</div>';

    loadEquipmentMaintenances(e.id);
    
    return s;
}

function edit(id) {
    var textBoxes = getTextBoxes(controller, arguments[1]);
    
    if (controller == "Equipments" && arguments[1] == 'equipment') {
        $('delivered' + id).disabled = false;
    }
    var list = constructTextBoxes(textBoxes, id);
    $('actions' + id).innerHTML = '<button onclick="saveEdit(\'' + id + '\', \'' + arguments[1] + '\')">Guardar</button> ' +
        '<span class="link red" onclick="cancelEdit(\'' + id + '\',' + list + ',\'' + arguments[1] + '\')">Cancelar</span> ' +
        '<button onclick="del(\'' + id + '\', \'' + arguments[1] + '\')">Borrar</button>';
}

function cancelEdit(id, list) {
    var textBoxes = getTextBoxes(controller, arguments[2]);
    
    if (controller == "Equipments" && arguments[2] == 'equipment') {
        $('delivered' + id).disabled = true;
    }
    
    deconstructTextBoxes(textBoxes, id, eval(list));
    $('actions' + id).innerHTML = '<button onclick="edit(\'' + id + '\', \'' + arguments[2] +  '\')">Editar</button> <button onclick="del(\'' + id + '\', \'' + arguments[2] +  '\')">Borrar</button>';
}

function saveEdit(id) {
    var textBoxes = getTextBoxes(controller, arguments[1]);
    var data = {'command' : 'edit', 'id' : id + '', 'list' : getEditedValuesList(textBoxes, id)};
    
    data.subcontroller = arguments[1];
    if (controller == "Equipments" && data.subcontroller == 'equipment') {
        $('delivered' + id).disabled = true;
    } else if (controller == "Equipments" && data.subcontroller == 'log') {
        data.id = data.id.substr(1);
    }
    doAjax(data);
}

function del(id) {
    var b = confirm("¿Está seguro que desea borrar este elemeto?");
    var data = {'command' : 'remove', 'id' : id + ''};
    
    data.subcontroller = arguments[1];
    if (controller == "Equipments" && data.subcontroller == 'log') {
        data.id = data.id.substr(1);
    }
    //if (controller == "Maintenances") {
    if (b) {
        //      var data = {'command' : 'remove', 'id' : id + ''};
        doAjax(data);
    }
    //} else if (controller == "Equipments") {
        
    //} else if (controller == "Lines") {
        
    //}
}

function getTextBoxes(controller, subcontroller) {
    var textBoxes = [];
    
    if (controller == "Maintenances") {
        textBoxes = maintenancesTextBoxes;
    } else if (controller == "Equipments" && subcontroller == 'equipment') {
        textBoxes = equipmentsTextBoxes;
    } else if (controller == "Equipments" && subcontroller == 'log') {
        textBoxes = logTextBoxes;
    } else if (controller == "Lines") {
        textBoxes = linesTextBoxes;
    }
    
    return textBoxes;
}

function constructTextBoxes(textBoxes, id) {
    var tmp = new Array();
    
    for (i = 0; i < textBoxes.length; i++) {
        tmp[i] = $(textBoxes[i] + id).innerHTML;
        $(textBoxes[i] + id).innerHTML = '<input value="' + $(textBoxes[i] + id).innerHTML + '"/>';
    }
    
    return getJSList(tmp);
}

function deconstructTextBoxes(textBoxes, id, list) {
    
    for (i = 0; i < textBoxes.length; i++) {
        $(textBoxes[i] + id).innerHTML = list[i];
    }
}

function getJSList(vec) {
    var values = "";
    
    for (i = 0; i < vec.length; i++) {
        values += ",\\'" + vec[i] + "\\'";
    }
    
    return "'[" + values.substr(1) + "]'";
}

function getEditedValuesList(textBoxes, id) {
    var list = new Array();
    
    for (i = 0; i < textBoxes.length; i++) {
        list[i] = $(textBoxes[i] + id).firstChild.value;
    }
    
    return list;
}

function observeCalInputs() {
    var inputs = $$('.cal input');
    for (i = 0; i < inputs.length; i++) {
        inputs[i].observe("click", openCalendar);
    }
}

function loadCalendar() {
    new Draggable($('lock'), {handle: "move", starteffect: Prototype.emptyFunction, endeffect: Prototype.emptyFunction});
    calendar = new scal('calendar', "selected-date", {
        updateformat: 'dd/mm/yyyy',
        exactweeks: true
    });
    //today = calendar.startdate;
}
function openCalendar(event) {
    var input = event.element();
    currentInput = input;
    try {
        var d = new Date();
        var aux = currentInput.value;
        aux = aux.split("/");
        if (aux != "") {
            year = parseInt(aux[2]);
            month = parseInt(aux[1]);
            day = parseInt(aux[0]);
            d.setFullYear(year, month - 1, day);
            calendar.setCurrentDate(d);
        } else {
            calendar.setCurrentDate(calendar.startdate);  
        }
    } catch (e) {
        calendar.setCurrentDate(calendar.startdate);
    }
    calendarSelection();
    Effect.Appear($('lock'), {duration: 0.4})
}
function calendarSelection() {
    currentInput.value = $('selected-date').innerHTML;
}
function closeCalendar() {
    Effect.Fade($('lock'), {duration: 0.4});
}
